-- player_inventory.lua

local player = FindMetaTable("Player")


--[[
Returns if player has 'quantity' of 'class' within their inventory
Loops for each inventory item and adds on how many it's found
Compares if found enough
]]--
function player:HasItem( class, quantity )
	if not ValidItem( class ) then return end
	quantity = quantity or 1

	count = self:CountItem( class )
	
	if count >= quantity then return true end
	return false
end

--[[
Returns how many of 'class' player has within player's inventory
--]]
function player:CountItem( class )
	if not ValidItem( class ) then return end
	
	count = 0
	for _, item in pairs( self.Items ) do
		if item.class == class then
			count = item.quantity
		end
	end
	return count
end

--[[
Gives a player 'quantity' of 'class'
If the item is stackable, it looks for the stack then adds on the quantity.
If the item is not, loops for the quantity and adds an item for each.
--]]
function player:GiveItem( class, quantity )
	if not ValidItem( class ) then return end
	quantity = quantity or 1

	if Items[class].Stackable then
		if self:HasItem( class ) then
			for _, item in pairs( self.Items ) do
				if item.class == class then
					item.quantity = item.quantity + quantity	
				end
			end
		else
			Item = { class = class, quantity = quantity }
			table.insert( self.Items, Item )
		end
	else
		for q = 1, quantity do
			Item = { class = class, quantity = 1 }
			table.insert( self.Items, Item )
		end
	end
	return true
end

--[[
Uses player:HasItem() to check if the player has what's needed. If not returns false.
Loops through items, if stackable takes. If not removes and carries on looping.
find = how many left to find
take = how many to take in that loop
--]]
function player:TakeItem( class, quantity )
	if not ValidItem( class ) then return end
	if not self:HasItem( class, quantity ) then return false end
	quantity = quantity or 1
	
	find = quantity
	while find > 0 do
		for k, item in pairs( self.Items ) do
			item[k] = self.Items
			if item.class == class then
				if Items[class].Stackable then
					if find == item.quantity then
						table.remove( self.Items, k )
					else
						self.Items[k].quantity = self.Items[k].quantity - find
					end
					return true
				else
					find = find - 1
					table.remove( self.Items, k )			
					break
				end
			end
		end
	end
end

concommand.Add("RP_ItemList", function( ply, cmd, args)
	ply:ChatPrint("Listing all your shit...")
	for k, v in pairs(ply.Items) do
		ply:ChatPrint("Item: " .. v.class .. " Quantity: " .. v.quantity)
	end
end )
concommand.Add("RP_ItemGive", function( ply, cmd, args )
	ply:GiveItem( args[1], tonumber(args[2]) )
end )
concommand.Add("RP_ItemTake", function( ply, cmd, args )
	ply:TakeItem( args[1], tonumber(args[2]) )
end )